﻿using Link_eLab.Jwt.Param;
using Link_eLab.Jwt.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Link_eLab.Jwt.Controllers
{
    /// <summary>
    /// 用户权限Controller
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly IAuthService AuthService;

        #region 构造函数

        /// <summary>
        /// 
        /// </summary>
        /// <param name="authService"></param>
        public AuthController(IAuthService authService)
        {
            AuthService = authService;
        }

        #endregion

        #region 用户登录

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="phone">电话号</param>
        /// <param name="password">密码</param>
        /// <param name="clientType">客户端</param>
        /// <returns>JSON结果集</returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("AccountLogin")]
        public ActionResult AccountLogin(string phone, string password, int clientType)
        {
            if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(password) || clientType <= 0)
            {
                return new JsonResult(new
                {
                    Code = -1,
                    Msg = "参数错误"
                });
            }

            JsonResult result = AuthService.AccessAuthorization(clientType, phone, password);

            return result;
        }

        #endregion

        #region 获取权限

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <returns>JSON结果集</returns>
        [Authorize("AuthJwt")]
        [HttpGet]
        [Route("GetPermission")]
        public ActionResult GetPermission()
        {
            var userId = User.Claims.First(i => i.Type == "userId").Value;
            JsonResult result = AuthService.GetPermission(userId);

            return result;
        }

        #endregion

        #region 获取我的个人信息

        /// <summary>
        /// 获取我的个人信息
        /// </summary>
        /// <returns>JSON结果集</returns>
        [Authorize("AuthJwt")]
        [HttpGet]
        [Route("Me")]
        public ActionResult Me()
        {
            JsonResult result = AuthService.GetAdmin(User.Claims.First(i => i.Type == "userId").Value);

            return result;
        }

        #endregion

        #region 修改密码

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="param">更新参数</param>
        /// <returns>JSON结果集</returns>
        [Authorize("AuthJwt")]
        [HttpPost]
        [Route("Password")]
        public ActionResult Password([FromBody] UpdatePwdModel param)
        {
            string userId = User.Claims.First(i => i.Type == "userId").Value;
            JsonResult result = AuthService.UpdatePassword(userId, param.OldPassword, param.NewPassword);

            return result;
        }

        #endregion
    }
}